<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>vue-birthday</title>
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
          crossorigin="anonymous">
    <style>
        [v-cloak] {
            visibility: hidden;
        }
    </style>
</head>
<body>
<div id="app" v-cloak>
    <div v-birthday="timeNow"></div>
    <div v-birthday="timeBefore"></div>
</div>
<script src="https://unpkg.com/vue"></script>
<!--<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"-->
<!--integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"-->
<!--crossorigin="anonymous"></script>-->
<script>
    function getFormatTime(timestamp) {
        let timer = Date.now() - timestamp;
        let tip = '';
        if (timer <= 0) {
            tip = '刚刚';
        } else if (Math.floor(timer/60) <= 0) {
            tip = '刚刚';
        } else if (timer < 3600) {
            tip = Math.floor(timer/60) + '分钟前';
        } else if(timer < 86400) {
            tip = Math.floor(timer/3600) + '小时前';
        } else if (timer/86400 <= 31) {
            tip = Math.floor(timer/86400) + '天前';
        } else {
            let date = new Date(timestamp);
            tip = date.getFullYear() + '年' + (date.getMonth()-0+1) + '月' + date.getDate() + '日';
        }
        return tip;
    }
    function getBirthday(timestamp) {
        let now = new Date();
        let birth = new Date(timestamp);
        let year = now.getFullYear() - birth.getFullYear();
        let month = now.getMonth() - birth.getMonth();
        let day = now.getDate() - birth.getDate();
        if (day < 0) {
            month--;
            day = now.getTime() - (new Date()).setFullYear(now.getFullYear(), now.getMonth()-1, birth.getDate());
        }
        if (month < 0) {
            year--;
            month = 12 + month;
        }

        return `已经出生了${year}岁${month}个月${day}天`;
    }
    Vue.directive('birthday', {
        bind(el, binding) {
            el.innerHTML = getBirthday(binding.value);
        }
    });
    let app = new Vue({
        el: '#app',
        data: {
            timeNow: (new Date()).setFullYear(2018, 4, 7),
            timeBefore: (new Date()).setFullYear(1996, 10, 2)
        }
    });
</script>
</body>
</html>